<ul class="nav nav-tabs">
    <li class="" id="li-token-login"><a href="#token-login-tab" data-toggle="tab">{{ _("Token Login") }}</a></li>
    <li class="" id="li-password-login" hidden><a href="#password-login-tab" data-toggle="tab">{{ _("Password Login") }}</a></li>
    <li class="hide" id="li-info"><a href="#info" data-toggle="tab">{{ _("Account") }}</a></li>
    <li class="hide" id="li-setting"><a href="#advanced" data-toggle="tab">{{ _("Settings") }}</a></li>
    <li class="hide" id="li-plans"><a href="#plans" data-toggle="tab">{{ _("Plans") }}</a></li>
    <li class="hide" id="li-history"><a href="#history" data-toggle="tab">{{ _("History") }}</a></li>
    <li class="hide" id="li-help"><a href="#help" data-toggle="tab">{{ _("Help") }}</a></li>
</ul>
<div class="tab-content">
    <div id="token-login-tab" class="tab-pane fade in hide">
        <form id="token-login-form" onSubmit="onTokenLoginSubmit(); return false;">
            <p >{{ _("Input login token from https://xx-net.com.") }}</p>
            <p>
                <label for="login-token">{{ _("Token") }}</label>
                <input id="login-token" type="text"/>
            </p>
            <p>
                <button class="btn btn-primary btn-block" type="submit">{{ _("Login") }}</button>
            </p>
        </form> <!-- #login-form -->
    </div>

    <div id="password-login-tab" class="tab-pane fade in ">
        <form id="password-login-form" onSubmit="onLoginSubmit(); return false;">
            <h4>{{ _("Login") }}</h4>
            <p>
                <label for="login-username">{{ _("Email") }}</label>
                <input id="login-username" type="text"/>
            </p>
            <p>
                <label for="login-password">{{ _("Password") }}</label>
                <input id="login-password" type="password"/>
            </p>
            <p>
                <button class="btn btn-primary btn-block" type="submit">{{ _("Login") }}</button>
            </p>
            <p class="text-center" hidden>
                <a id="register-trigger" href="javascript:void(0);">{{ _("Haven't an account?") }}</a>
            </p>
            <p class="text-center">
                <a id="reset-password-trigger" href="javascript:void(0);">{{ _("Forget password?") }}</a>
            </p>
        </form> <!-- #login-form -->

        <form id="request-reset-form" class="hide" onSubmit="onResetRequest(); return false;">
            <h4>{{ _("Reset password") }}</h4>
            <p class="p80" >
                <label for="request-reset-username">{{ _("Email") }}</label>
                <input id="request-reset-username" type="text"/>
            </p>
            <p>
                <button class="btn btn-primary btn-block p80" type="submit">{{ _("Next") }}</button>
            </p>
        </form> <!-- #register-form -->

        <form id="reset-password-check-form" class="hide" onSubmit="onResetPasswordCheck(); return false;">
            <h4>{{ _("Input confirmation code") }}</h4>
            <p >{{ _("The confirmation code has sent to your email, please check your email box.") }}</p>
            <p class="p80" >
                <label for="reset-confirmation-code">{{ _("Confirmation Code") }}</label>
                <input id="reset-confirmation-code" type="text"/>
            </p>
            <p>
                <button class="btn btn-primary btn-block p80" type="submit">{{ _("Next") }}</button>
            </p>
        </form> <!-- #register-form -->

        <form id="change-password-form" class="hide" onSubmit="onChangePassword(); return false;">
            <h4>{{ _("Set new password") }}</h4>
            <p >{{ _("Please input your new password.") }}</p>
            <p class="p80" >
                <label for="new-password">{{ _("Password") }}</label>
                <input id="new-password" type="password"/>
            </p>
            <p class="p80" >
                <label for="new-password2">{{ _("Confirm your password") }}</label>
                <input id="new-password2" type="password"/>
            </p>
            <p>
                <button class="btn btn-primary btn-block p80" type="submit">{{ _("Submit") }}</button>
            </p>
        </form> <!-- #register-form -->

        <div id="password-reset-successful" class="hide" >
            <h4>{{ _("Your password has reset successfully.") }}</h4>
            <p >{{ _("Please use your new password to login.") }}</p>
            <p>
                <button class="btn btn-primary btn-block p80" id="goto-login-trigger">{{ _("Login") }}</button>
            </p>
        </div> <!-- #register-form -->

        <form id="register-form" class="hide" onSubmit="onRegisterSubmit(); return false;">
            <h4>{{ _("Register") }}</h4>
            <p>
                <label for="register-username">{{ _("Email") }}</label>
                <input id="register-username" type="text"/>
            </p>
            <p>
                <label for="register-password">{{ _("Password") }}</label>
                <input id="register-password" type="password"/>
            </p>
            <p>
                <label for="register-promoter">{{ _("Promoter(Optional)") }}</label>
                <input id="register-promoter" type="text"/>
            </p>
            <p>
                <button class="btn btn-primary btn-block" type="submit">{{ _("Register") }}</button>
            </p>
            <p class="text-center">
                <a id="login-trigger" href="javascript:void(0);">{{ _("Already have an account?") }}</a>
            </p>
        </form> <!-- #register-form -->
    </div>
    <div id="info" class="tab-pane fade in active">
        <div id="account-information" class="hide">
            <div class="section">
<!--                <h4>{{ _("Summary") }}</h4>-->
                <div class="row-fluid">
                    <div class="span2">
                        <label for="login-account">{{ _("Account") }}</label>
                    </div> <!-- .span4 -->
                    <div class="span6">
                        <p>
                            <span id="login-account">N/a</span>
                            <a id="logout-trigger" href="javascript:void(0)">[{{ _("Logout") }}]</a>
                        </p>
                    </div> <!-- .span8 -->
                </div> <!-- .row-fluid -->
                <div class="row-fluid">
                    <div class="span2">
                        <label for="credit">{{ _("Credit") }}</label>
                    </div> <!-- .span4 -->
                    <div class="span4">
                        <p>
                            <span id="credit">N/a</span>
                            <!-- <a id="charge-trigger" href="javascript:void(0);">[{{ _("Charge") }}]</a> -->
<!--                            <a id="transfer-credit-trigger" href="javascript:void(0);">[{{ _("Transfer") }}]</a>-->
                        </p>
                    </div> <!-- .span8 -->
                </div> <!-- .row-fluid -->
                <div class="row-fluid">
                    <div class="span2">
                        <label for="openai_balance">{{ _("OpenAI Credit") }}</label>
                    </div> <!-- .span4 -->
                    <div class="span4">
                        <p>
                            <span id="openai_balance">N/a</span>
                            <!-- <a id="charge-trigger" href="javascript:void(0);">[{{ _("Charge") }}]</a> -->
<!--                            <a id="transfer-credit-trigger" href="javascript:void(0);">[{{ _("Transfer") }}]</a>-->
                        </p>
                    </div> <!-- .span8 -->
                </div> <!-- .row-fluid -->
            </div> <!-- .section -->
            <div class="section">
                <h4>{{ _("Available Plan") }}:</h4>
                <p id="no-bandwidth">&nbsp;&nbsp;&nbsp;{{ _("No Valid Plan available.") }}</p>
                <div id="available-plan">
                    <table id="available-bandwidth" class="table hide">
                        <thead>
                            <tr>
                                <th>{{ _("Expire Time") }}</th>
    <!--                            <th>{{ _("Left Bandwidth") }}</th>-->
                            </tr>
                        </thead>
                        <tbody></tbody>
                    </table>
                </div>
            </div> <!-- .section -->
        </div> <!-- #account-information -->
    </div> <!-- #info -->
    <div id="advanced" class="tab-pane fade in">
        <form id="adv-setting" onSubmit="onAdvSettingSubmit(); return false;">
            <div class="row-fluid">
                <div class="span3">
                    <label for="server-selector">{{ _( "server" ) }}</label>
                </div>
                <div class="span6">
                    <select id="server-selector">
                        <option value="auto">{{ _( "AUTO" ) }}</option>
                    </select>
                </div>
            </div>
            <br/>

            <div class="row-fluid" hidden>
                <div class="span3">
                    <label for="promoter">{{ _("Promoter (<a href='https://github.com/XX-net/XX-Net/wiki/X-Tunnel-Promote-Plan'>Help</a>)") }}</label>
                </div>
                <div class="span6">
                    <input id="promoter" type="text"/>
                </div>
            </div>
            <br/>

            <div class="row-fluid">
                <div class="span12">
                    <button class="btn btn-primary btn-block" type="submit">{{ _("Submit") }}</button>
                </div>
            </div>
        </form>
    </div> <!-- #info -->
    <div id="plans" class="tab-pane fade in" style="padding-left:0">
        <div class="section">
            <h4>{{ _("Plans and Pricing") }}</h4>
            <div class="row-fluid">
                <ul class="thumbnails" id="plan-list">

                </ul>
            </div> <!-- .row-fluid -->
        </div> <!-- .section -->
        <div class="section" hidden>
            <h4>{{ _("Billing History") }}</h4>
            <p id="no-billing-history">{{ _("No billing history.") }}</p>
            <table id="billing-history" class="table hide">
                <thead>
                    <tr>
                        <th>{{ _("Time") }}</th>
                        <th>{{ _("Description") }}</th>
                    </tr>
                </thead>
                <tbody></tbody>
            </table>
        </div> <!-- .section -->
    </div> <!-- #plans -->
    <div id="history" class="tab-pane fade in">
        <div class="row-fluid">
            <div class="span6">
                <h4>{{ _("History") }}</h4>
            </div> <!-- .span6 -->
            <div class="span6 text-right">
                <button class="btn btn-primary" id="get-history-button">{{ _("Get") }}</button>
            </div> <!-- .span6 -->
        </div> <!-- .row-fluid -->
        <table id="history-list" class="table table-bordered table-striped">
            <thead>
                <tr>
                    <th>{{ _("Time") }}</th>
                    <th>{{ _("Action") }}</th>
                </tr>
            </thead>
            <tbody>
            </tbody>
        </table>
    </div> <!-- #history -->
    <div id="help" class="tab-pane fade in">
        <h4>{{ _("Help") }}</h4>
        <div class="row-fluid">
            <div class="span4">
                <label>SOCKS5</label>
            </div> <!-- .span4 -->
            <div class="span8">
                <p>127.0.0.1:1080</p>
            </div> <!-- .span8 -->
        </div> <!-- .row-fluid -->
        <div class="row-fluid">
            <div class="span4">
                <label>Wiki</label>
            </div> <!-- .span4 -->
            <div class="span8">
                <p><a href='{{ _( "https://github.com/XX-net/XX-Net/wiki/How-to-use-XTunnel" ) }}' target="_blank">X-Tunnel Wiki@GitHub</a></p>
            </div> <!-- .span8 -->
        </div> <!-- .row-fluid -->

                <div class="row-fluid">
                    <div class="span4">
                        <label for="promote_code">{{ _("Promote Code (<a href='https://github.com/XX-net/XX-Net/wiki/X-Tunnel-Promote-Plan'>Help</a>)") }}</label>
                    </div> <!-- .span4 -->
                    <div class="span8">
                        <p>
                            <span id="promote_code">N/a</span>
                        </p>
                    </div> <!-- .span8 -->
                    <div class="hidden">
                            <input type="text" value="" id="copyText">
                    </div>
                </div> <!-- .row-fluid -->
    </div> <!-- #help -->
</div> <!-- #tab-content -->

<!-- Modals -->
<form id="charge-modal" class="modal hide fade" action="https://www.paypal.com/cgi-bin/webscr" method="POST" target="_blank">
    <div class="modal-header">
        <button type="button" class="close" data-dismiss="modal" aria-hidden="true">&times;</button>
        <h5>{{ _("Charge") }}</h5>
    </div> <!-- .modal-header -->
    <div class="modal-body">
        <div class="alert alert-warning hide">{{ _("You haven't enough credit. Please charge first.") }}</div> <!-- .alert-warning -->
        <!-- Plan Field -->
        <input type="hidden" name="on0" value="Plan">
        <label for="charge-plan">{{ _("Plan") }}:</label>
        <select id="charge-plan" name="os0">
        </select>
        <!-- Account Field -->
        <input type="hidden" name="on1" value="account">
        <input class="login-account" type="hidden" name="os1">
    </div> <!-- .modal-body -->
    <div class="modal-footer">
        <input type="hidden" name="cmd" value="_s-xclick">
        <input type="hidden" name="hosted_button_id" value="">
        <input type="hidden" name="currency_code" value="USD">
        <a href="javascript:void(0);" class="btn" data-dismiss="modal">{{ _("Close") }}</a>
        <button class="btn btn-primary">{{ _("Buy Now") }}</button>
    </div> <!-- .modal-footer -->
</form> <!-- #charge-modal -->

<div id="transfer-credit-modal" class="modal hide fade">
    <div class="modal-header">
        <button type="button" class="close" data-dismiss="modal" aria-hidden="true">&times;</button>
        <h5>{{ _("Transfer Credit") }}</h5>
    </div> <!-- .modal-header -->
    <div class="modal-body">
        <div class="alert alert-error hide"></div> <!-- .alert-error -->
        <p>
            <label for="transfer-credit-username">{{ _("Username transfer to") }}</label>
            <input id="transfer-credit-username" type="text" placeholder='{{ _("Email Address") }}'/>
        </p>
        <p>
            <label for="transfer-credit-amount">{{ _("Credit to transfer") }} (<strong>USD</strong>)</label>
            <input id="transfer-credit-amount" type="text" value="0" onkeyup="isDecimalNumber(this)"/>
        </p>
    </div> <!-- .modal-body -->
    <div class="modal-footer">
        <a href="javascript:void(0);" class="btn" data-dismiss="modal">{{ _("Close") }}</a>
        <button class="btn btn-primary">{{ _("Transfer") }}</button>
    </div> <!-- .modal-footer -->
</div> <!-- #transfer-credit-modal -->

<div id="transfer-bandwidth-modal" class="modal hide fade">
    <div class="modal-header">
        <button type="button" class="close" data-dismiss="modal" aria-hidden="true">&times;</button>
        <h5>{{ _("Transfer Bandwidth") }}</h5>
    </div> <!-- .modal-header -->
    <div class="modal-body">
        <div class="alert alert-error hide"></div> <!-- .alert-error -->
        <p>
            <label for="transfer-bandwidth-username">{{ _("Username transfer to") }}</label>
            <input id="transfer-bandwidth-username" type="text" placeholder='{{ _("Email Address") }}'/>
        </p>
        <p>
            <label for="transfer-bandwidth-amount">{{ _("Bandwidth to transfer") }} (<strong>MB</strong>)</label>
            <input id="transfer-bandwidth-amount" type="text" onkeyup="isDecimalNumber(this)"/>
        </p>
    </div> <!-- .modal-body -->
    <div class="modal-footer">
        <input type="hidden" id="bandwidth-expire-time">
        <a href="javascript:void(0);" class="btn" data-dismiss="modal">{{ _("Close") }}</a>
        <button class="btn btn-primary">{{ _("Transfer") }}</button>
    </div> <!-- .modal-footer -->
</div> <!-- #transfer-bandwidth-modal -->

<!-- JavaScript -->
<script type="text/javascript">
    title('{{ _( "X-Tunnel Configuration" ) }}');
</script>
<script type="text/javascript">

    $('a[href="#plans"]').click(function () {
        window.refresh_timer.stop();
        AdvSettingInit();
    });

    $(function () {
        window.refresh_timer = $.timer(function () {
            getUserInfo(0);
        });

        window.refresh_timer.set({
            time: 1000,
            autostart: true
        });

        var force_update = 0;
        var navigationType = performance.navigation.type;
        if (navigationType === performance.navigation.TYPE_BACK_FORWARD) {
            // console.log("Back/Forward button");
        } else if (navigationType === performance.navigation.TYPE_RELOAD) {
            console.log("Reloaded");
            force_update = 1;
        } else if (navigationType === performance.navigation.TYPE_NAVIGATE) {
            // console.log("Normal navigation");
        }

        tip('{{ _("Logining ...") }}', 'info', false);
        $('button[type=submit]', '#login-form').html('{{ _("Please wait ...") }}');
        $('button[type=submit]', '#login-form').attr('disabled', 'disabled');
        getUserInfo(force_update);
    });
</script>
<script type="text/javascript">
    $('#promote_code').dblclick(function () {
        var promote_code = $('#promote_code').val();
        $('#copyText').html(promote_code);

        /* Get the text field */
        var copyText = document.getElementById("copyText");

        /* Select the text field */
        copyText.select();

        /* Copy the text inside the text field */
        document.execCommand("copy");

        tip('{{ _("Promote Code copied to Clipboard.") }} ', 'info', false);
        window.refresh_timer.stop();
    });
</script>
<!-- Summary -->
<script type="text/javascript">
    $('#register-trigger').click(function () {
        $('#password-login-form').addClass('hide');
        $('#register-form').removeClass('hide');
    });
    $('#reset-password-trigger').click(function () {
        $('#password-login-form').addClass('hide');
        $('#request-reset-form').removeClass('hide');
    });
    $('#login-trigger').click(function () {
        $('#register-form').addClass('hide');
        $('#password-login-form').removeClass('hide');
    });
    $('#goto-login-trigger').click(function () {
        $('#password-reset-successful').addClass('hide');
        $('#password-login-form').removeClass('hide');
    });
</script>
<script type="text/javascript">
    var standalone = window.navigator.standalone,
        userAgent = window.navigator.userAgent.toLowerCase(),
        safari = /safari/.test( userAgent ),
        ios = /iphone|ipod|ipad/.test( userAgent );
    var uiwebview = false;

    if( ios ) {
        if ( !standalone && safari ) {
            //browser
        } else if ( standalone && !safari ) {
            //standalone
        } else if ( !standalone && !safari ) {
            uiwebview = true;
        };
    } else {
        if (typeof window.Android !== "undefined"){
            uiwebview = true;
        }
    }

    function show_login_form(){
        $('ul.nav-tabs > li').addClass('hide');
        $('#li-token-login').removeClass('hide');
        $('#li-password-login').removeClass('hide');

        if(uiwebview || true) {
            $('#li-token-login').addClass('active');

            $('#password-login-tab').addClass('hide');

            $('#token-login-tab').removeClass('hide');
            $('#token-login-tab').addClass('active');
        } else {
            $('#li-password-login').addClass('active');

            $('#token-login-tab').addClass('hide');

            $('#password-login-tab').removeClass('hide');
            $('#password-login-tab').addClass('active');
        }

        $('#account-information').addClass('hide');
    }
    show_login_form();

    function show_uinfo_menus() {
        $('#token-login-tab').removeClass('active');
        $('#password-login-tab').removeClass('active');
        $('#info').addClass('in');
        $('#info').addClass('active');

        $('#li-token-login').removeClass('active');
        $('#li-password-login').removeClass('active');
        $('#li-token-login').addClass('hide');
        $('#li-password-login').addClass('hide');

        $('#li-info').removeClass('hide');
        $('#li-info').addClass('active');
        $('#li-setting').removeClass('hide');
        if (!uiwebview) {
            $('#li-plans').removeClass('hide');
            $('#li-history').removeClass('hide');
            $('#li-help').removeClass('hide');
        }
    }

    function getUserInfo(force) {
        var url = '/module/x_tunnel/control/info';
        if (force) {
            url = url + "?force=1";
        }

        $.ajax({
            type: 'GET',
            url: url,
            dataType: 'JSON',
            success: function (result) {
                if (result['res'] == 'logout') {
                    tipClose();
                    $('#login-form').removeClass('hide');
                    $('#account-information').addClass('hide');

                    $('button[type=submit]', '#login-form').html('{{ _("Login") }}');
                    $('button[type=submit]', '#login-form').removeAttr('disabled');

                    window.refresh_timer.stop();
                    return;
                }

                if (result['res'] == 'login_process') {
                    tip('{{ _("Logining ...") }}', 'info', false);
                    window.refresh_timer.play();
                    return;
                }

                if (result['res'] != 'success') {
                    tip('{{ _("Connect to server fail:") }}' + result['reason'], 'warning', false);
                    $('#login-username').val(result['login_account']);
                    $('#login-password').val('_HiddenPassword');

                    $('button[type=submit]', '#login-form').html('{{ _("Login") }}');
                    $('button[type=submit]', '#login-form').removeAttr('disabled');

                    window.refresh_timer.stop();

                    return;
                }

                tipClose();
                window.refresh_timer.play();

                show_uinfo_menus();

                $('#account-information').removeClass('hide');

                $('#login-account').html(result['login_account']);
                $('.login-account').val(result['login_account']);
                $('#promote_code').html(result['promote_code']);
                window.promote_code = result['promote_code'];
                $('#promoter').html(result['promoter']);
                $('#credit').html(getCreditForHumanReading(result['balance']));
                $('#openai_balance').html("$" + parseFloat(result['openai_balance']).toFixed(6));

                $('#bandwidth').html(getBandwidthForHumanReading(result['quota']));

                getAvailableBandwidth(result['quota_list']);

                update_paypal_button_id(result['paypal_button_id']);
                updatePlans(result['plans']);

                window.refresh_timer.stop();
            }
        });
    }
</script>
<script type="text/javascript">
    function getAvailableBandwidth(bandwidthList) {
        $('#available-bandwidth tbody').empty();

        var has_plan = false;
        if (bandwidthList['current']) {
            displayBandwidth(bandwidthList['current']);
            has_plan = true;
        }
        if (bandwidthList['backup']) {
            bandwidthList['backup'].forEach(function (entry) {
                displayBandwidth(entry);
                has_plan = true;
            });
        }

        if (has_plan) {
            $('#no-bandwidth').addClass('hide');
            $('#available-plan').removeClass('hide');
            $('#available-bandwidth').removeClass('hide');
        }else{
            $('#no-bandwidth').removeClass('hide');
            $('#available-plan').addClass('hide');
            $('#available-bandwidthn').addClass('hide');
        }
    }

</script>
<script type="text/javascript">
    function update_paypal_button_id(id){
        $('input[name$="hosted_button_id"]').val(id);
    }

    function plan_compare(a, b){
        if (a["cost"] > b["cost"]) return 1;
        if (b["cost"] > a["cost"]) return -1;
        return 0;
    }

    function updatePlans(plans) {
        $('#plan-list').empty();
        $('#charge-plan').empty();

        var unordered_plans = [];
        for ( var plan in plans ) {
            var pe = plans[plan];
            pe["plan"] = plan;
            unordered_plans.push(pe);
        }

        var ordered_plans = unordered_plans.sort(plan_compare);

        //for ( var plan_info in ordered_plans ) {
        ordered_plans.forEach( function( plan_info ) {
            var plan = plan_info["plan"];
            var title = plan_info["title"];
            var cost = plan_info["cost"];
            var quota_G = plan_info["quota_G"];
            var time_limit_month = plan_info["time_limit_month"];
            var monthly_cost = cost / time_limit_month;

            var text = `<div class="plan-block span4">
                        <div class="thumbnail">
                            <div class="caption">
                                <p class="price" style="text-align:center">
                                    <font style="font-size:2rem"
                                        <sup>$</sup>
                                         %s
                                     </font>
                                     {{ _("Per Month") }}
                                </p>

                                <ul class="details">
                                    <li>
                                        <p style="text-align:center">
                                            %s
                                            {{ _("Months") }}
                                        </p>
                                    </li>
                                    <li>
                                        <p style="text-align:center">
                                            $
                                            %s
                                            {{ _("Total") }}
                                        </p>
                                    </li>
                                </ul>
                                <p>
                                    <a href="javascript:void(0);" id="%s" title="%s" class="btn btn-primary btn-block plan-trigger">{{ _("Buy Now") }}</a>
                                </p>
                            </div> <!-- .caption -->
                        </div> <!-- .thumbnail -->
                    </div>`.format(monthly_cost, time_limit_month, cost, plan, title);
            $('#plan-list').append(text);
            $('#charge-plan').append('<option value="%s">{{ _("%s") }} $%s</option>'.format(title, title, cost));

        });
    }
</script>

<script type="text/javascript">
    function displayBandwidth(bandwidthRecord) {
        var expireTime          = bandwidthRecord['end_time'],
            expireTimeObj       = new Date(expireTime * 1000);
            expireTimeString    = expireTimeObj.toISOString().substring(0, 10);
            bandwidth           = getBandwidthForHumanReading(bandwidthRecord['quota']);

        $('#available-bandwidth tbody').append('<tr><td><span class="expire-time" data-value="%s">%s</span></td></tr>'.format(expireTime, expireTimeString));
    }
</script>
<script type="text/javascript">
    function getCreditForHumanReading(credit) {
        if (parseFloat(credit) == 0) {
            $('#transfer-credit-trigger').addClass('hide');
        } else {
            $('#transfer-credit-trigger').removeClass('hide');
        }
        return '$ ' + parseFloat(credit).toFixed(2);
    }
</script>
<script type="text/javascript">
    function getBandwidthForHumanReading(bandwidth) {
        var base        = 1000,
            bandwidth   = Math.round(bandwidth) / base / base;

        if (bandwidth > base) {
            bandwidth = bandwidth / base;
            bandwidth = parseFloat(bandwidth).toFixed(2) + ' GB';
        } else {
            bandwidth = parseFloat(bandwidth).toFixed(2) + ' MB';
        }
        return bandwidth;
    }
</script>
<script type="text/javascript">
    function isEmailLegal(email) {
        var regx = /^(([^<>()[\]\\.,;:\s@"]+(\.[^<>()[\]\\.,;:\s@"]+)*)|(".+"))@((\[[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}])|(([a-zA-Z\-0-9]+\.)+[a-zA-Z]{2,}))$/;
        return regx.test(email);
    }

    function isEmailQualified(email) {
        if (!isEmailLegal(email)) return false;
        var host = email.split('@')[1];
        var weakhosts = ['qq.com', 'sina.cn', 'sina.com', '126.com', '163.com', '163.net', 'yeah.net'];
        for (var i in weakhosts) {
            if (host.indexOf(weakhosts[i]) >= 0) {
                return false;
            }
            /*
            var regx = /^$/;
            if (regx.test(host)) {
                return false;
            }
            */
        }
        return true;
    }

    function isPswLegal(password) {
        var regx = /^[a-zA-Z0-9_~!@#$%^&()+\-*/=.,:;'"<>\?\[\]\{\}]{6,20}$/;
        return regx.test(password);
    }
</script>
<script type="text/javascript">
    function onTokenLoginSubmit() {
        var login_token = $('#login-token').val();

        if (!login_token){
            tip('{{ _("Please input login token." )}}', 'error', false);
            return;
        }

        tip('{{ _("Logining ...") }}', 'info', false);
        $('button[type=submit]', '#token-login-form').html('{{ _("Please wait ...") }}');
        $('button[type=submit]', '#token-login-form').attr('disabled', 'disabled');
        return doTokenLoginAction(login_token);
    }

    function doTokenLoginAction(login_token) {
        var postData = {
            'login_token': login_token,
        };

        $.ajax({
            type: 'POST',
            url: '/module/x_tunnel/control/token_login',
            data: postData,
            dataType: 'JSON',
            success: function (result) {
                if (result['res'] == 'success') {
                    getUserInfo(0);
                } else {
                    if (result['reason'] == "status:'UNKNOWN'" || result['reason'] == "status:False") {
                        tip('{{ _("Connect to server fail, check Front log first.") }}', 'warning', false);
                    } else if (result['reason'] == "auth fail") {
                        tip('{{ _("Incorrect Email or password.") }}', 'error', false);
                    } else if (result['reason'] == "token invalid") {
                        tip('{{ _("Invalid token.") }}', 'error', false);
                    } else {
                        tip('{{ _("Login fail:") }}' + result['reason'], 'error', false);
                    }

                    $('button[type=submit]', '#token-login-form').html('{{ _("Login") }}');
                    $('button[type=submit]', '#token-login-form').removeAttr('disabled');
                }
            }
        });
    }

    function onLoginSubmit() {
        var username = $('#login-username').val(),
            password = $('#login-password').val();

        if (!isEmailLegal(username)) {
            tip('{{ _("Email seems invalid." )}}', 'error', false);
            return;
        } else if (password.length < 6) {
            tip('{{ _("Password needs at least 6 characters, and no more than 20.") }}', 'error', false);
            return;
        }

        tip('{{ _("Logining ...") }}', 'info', false);
        $('button[type=submit]', '#login-form').html('{{ _("Please wait ...") }}');
        $('button[type=submit]', '#login-form').attr('disabled', 'disabled');
        return doLoginAction(username, password);
    }
    function onResetRequest() {
        var username = $('#request-reset-username').val();

        if (!isEmailLegal(username)) {
            tip('{{ _("Email seems invalid." )}}', 'error', false);
            return;
        }

        tip('{{ _("Loading ...") }}', 'info', false);
        $('button[type=submit]', '#request-reset-form').html('{{ _("Please wait ...") }}');
        $('button[type=submit]', '#request-reset-form').attr('disabled', 'disabled');
        return doRequestResetPassword(username);
    }
    function onResetPasswordCheck() {
        var username = $('#request-reset-username').val();
        var code = $('#reset-confirmation-code').val();

        if (code.length < 6) {
            tip('{{ _("Please input invalid confirmation code." )}}', 'error', false);
            return;
        }

        tip('{{ _("Loading ...") }}', 'info', false);
        $('button[type=submit]', '#reset-password-check-form').html('{{ _("Please wait ...") }}');
        $('button[type=submit]', '#reset-password-check-form').attr('disabled', 'disabled');
        return doResetPasswordCheck(username, code);
    }
    function onChangePassword() {
        var username = $('#request-reset-username').val();
        var code = $('#reset-confirmation-code').val();
        var password = $('#new-password').val();
        var password2 = $('#new-password2').val();

        if (password.length < 6) {
            tip('{{ _("Password needs at least 6 characters, and no more than 20.") }}', 'error', false);
            return;
        } else if (password != password2) {
            tip('{{ _("Passwords are not match.") }}', 'error', false);
            return;
        }

        tip('{{ _("Loading ...") }}', 'info', false);
        $('button[type=submit]', '#change-password-form').html('{{ _("Please wait ...") }}');
        $('button[type=submit]', '#change-password-form').attr('disabled', 'disabled');
        return doChangePassword(username, code, password);
    }
</script>
<script type="text/javascript">
    function doLoginAction(username, password) {
        var postData = {
            'username': username,
            'password': password,
            'is_register': 0
        };

        $.ajax({
            type: 'POST',
            url: '/module/x_tunnel/control/login',
            data: postData,
            dataType: 'JSON',
            success: function (result) {
                if (result['res'] == 'success') {
                    getUserInfo(0);
                } else {
                    if (result['reason'] == "status:'UNKNOWN'" || result['reason'] == "status:False") {
                        tip('{{ _("Connect to server fail, check Front log first.") }}', 'warning', false);
                    } else if (result['reason'] == "auth fail") {
                        tip('{{ _("Incorrect Email or password.") }}', 'error', false);
                    } else if (result['reason'] == "account not exist") {
                        tip('{{ _("Incorrect Email or password.") }}', 'error', false);
                    } else if (result['reason'] == "status:602") {
                        tip('{{ _("Login failed, please try login using token.") }}', 'error', false);
                    } else {
                        tip('{{ _("Login fail:") }}' + result['reason'], 'error', false);
                    }

                    $('button[type=submit]', '#login-form').html('{{ _("Login") }}');
                    $('button[type=submit]', '#login-form').removeAttr('disabled');
                }
            }
        });
    }
    function doRequestResetPassword(username) {
        var postData = {
            'stage': "request_reset_password",
            'username': username,
        };

        $.ajax({
            type: 'POST',
            url: '/module/x_tunnel/control/reset_password',
            data: postData,
            dataType: 'JSON',
            success: function (result) {
                $('button[type=submit]', '#request-reset-form').html('{{ _("Next") }}');
                $('button[type=submit]', '#request-reset-form').removeAttr('disabled');

                if (result['res'] == 'success') {
                    $('#request-reset-form').addClass('hide');
                    $('#reset-password-check-form').removeClass('hide');
                    tipClose();
                } else {
                    if (result['reason'] == "status:'UNKNOWN'" || result['reason'] == "network_fail") {
                        tip('{{ _("Connect to server fail, check Front log first.") }}', 'warning', false);
                    } else if (result['reason'] == "account not exists") {
                        tip('{{ _("Account not exist.") }}', 'error', false);
                    } else if (result['reason'] == "try again later") {
                        tip('{{ _("Try again later.") }}', 'error', false);
                    } else {
                        tip('{{ _("Request fail:") }}' + result['reason'], 'error', false);
                    }
                }
            }
        });
    }
    function doResetPasswordCheck(username, code) {
        var postData = {
            'stage': "reset_password_check",
            'username': username,
            'code': code,
        };

        $.ajax({
            type: 'POST',
            url: '/module/x_tunnel/control/reset_password',
            data: postData,
            dataType: 'JSON',
            success: function (result) {
                $('button[type=submit]', '#eset-password-check-form').html('{{ _("Next") }}');
                $('button[type=submit]', '#eset-password-check-form').removeAttr('disabled');

                if (result['res'] == 'success') {
                    $('#reset-password-check-form').addClass('hide');
                    $('#change-password-form').removeClass('hide');
                    tipClose();
                } else {
                    if (result['reason'] == "status:'UNKNOWN'" || result['reason'] == "network_fail") {
                        tip('{{ _("Connect to server fail, check Front log first.") }}', 'warning', false);
                    } else if (result['reason'] == "account not exists") {
                        tip('{{ _("Account not exist.") }}', 'error', false);
                    } else if (result['reason'] == "code expired") {
                        tip('{{ _("Confirmation code expired, please restart again.") }}', 'error', false);
                    } else if (result['reason'] == "exceed max retry times") {
                        tip('{{ _("You have exceeded the retry limitation.") }}', 'error', false);
                    } else if (result['reason'] == "code not match") {
                        tip('{{ _("The code is not match, please check your code.") }}', 'error', false);
                    } else {
                        tip('{{ _("Request fail:") }}' + result['reason'], 'error', false);
                    }
                }
            }
        });
    }
    function doChangePassword(username, code, password) {
        var postData = {
            'stage': "change_password",
            'username': username,
            'code': code,
            'password': password,
        };

        $.ajax({
            type: 'POST',
            url: '/module/x_tunnel/control/reset_password',
            data: postData,
            dataType: 'JSON',
            success: function (result) {
                $('button[type=submit]', '#change-password-form').html('{{ _("Submit") }}');
                $('button[type=submit]', '#change-password-form').removeAttr('disabled');

                if (result['res'] == 'success') {
                    $('#change-password-form').addClass('hide');
                    $('#password-reset-successful').removeClass('hide');

                    $('#request-reset-username').val("");
                    $('#reset-confirmation-code').val("");
                    tipClose();
                } else {
                    if (result['reason'] == "status:'UNKNOWN'" || result['reason'] == "network_fail") {
                        tip('{{ _("Connect to server fail, check Front log first.") }}', 'warning', false);
                    } else if (result['reason'] == "account not exists") {
                        tip('{{ _("Account not exist.") }}', 'error', false);
                    } else if (result['reason'] == "code expired") {
                        tip('{{ _("Confirmation code expired, please restart again.") }}', 'error', false);
                    } else if (result['reason'] == "exceed max retry times") {
                        tip('{{ _("You have exceeded the retry limitation.") }}', 'error', false);
                    } else if (result['reason'] == "code not match") {
                        tip('{{ _("The code is not match, please check your code.") }}', 'error', false);
                    } else {
                        tip('{{ _("Request fail:") }}' + result['reason'], 'error', false);
                    }
                }
            }
        });
    }
</script>
<script type="text/javascript">
    function onRegisterSubmit() {
        var username = $('#register-username').val(),
            password = $('#register-password').val();
        var promoter = $('#register-promoter').val();

        if (!isEmailLegal(username)) {
            tip('{{ _("Email seems invalid." )}}', 'error', false);
            return;
        } else if (!isEmailQualified(username)) {
            tip('{{ _("Do NOT use Chinese-service-provider\'s Email!") }}', 'error', false);
            return;
        } else if (password.length < 6 || password.length > 20) {
            tip('{{ _("Password needs at least 6 charactors, and no more than 20.") }}', 'error', false);
            return;
        } else if (!isPswLegal(password)) {
            tip('{{ _("Password seems invalid.") }}{{ _("(available:a-zA-Z0-9_~!@#$%^&()+-*/=.,:;\'\"<>\?[]{})") }}', 'error', false);
            return;
        } else if (promoter.length != 0 && promoter.length != 8) {
            tip('{{ _("Promoter is invalid.") }}', 'error', false);
            return;
        }

        $('button[type=submit]', '#register-form').html('{{ _("Please wait ...") }}');
        $('button[type=submit]', '#register-form').attr('disabled', 'disabled');
        return doRegisterAction(username, password, promoter);
    }
</script>
<script type="text/javascript">
    function doRegisterAction(username, password, promoter) {
        var postData = {
            'username': username,
            'password': password,
            'promoter': promoter,
            'is_register': 1
        };

        $.ajax({
            type: 'POST',
            url: '/module/x_tunnel/control/register',
            data: postData,
            dataType: 'JSON',
            success: function (result) {
                if (result['res'] == 'success') {
                    // register success, hide '#register-form' and login.
                    // $('#register-form').addClass('hide');
                    tip('{{ _("Registered successfully, ") }}{{ _("Logining ...") }}', 'info', false);

                    return doLoginAction(username, password);
                } else {
                    if (result['reason'] == 'user exist') {
                        tip('{{ _("Email has been taken by another user.") }}', 'error', false);
                    } else if (result['reason'] == 'promoter not exist') {
                        tip('{{ _("Promoter not exist, check it or keep it empty.") }}', 'error', false);
                    } else {
                        tip('{{ _("Unknown error occurred.") }}', 'error', false);
                    }

                    $('button[type=submit]', '#register-form').html('{{ _("Register") }}');
                    $('button[type=submit]', '#register-form').removeAttr('disabled');
                }
            }
        });
    }
</script>
<script type="text/javascript">
    $('a[href="#advanced"]').click(function () {
        window.refresh_timer.stop();
        AdvSettingInit();
    });

    function AdvSettingInit() {
        //$("#server-selector").val('auto');
        var pageRequests = {'cmd': 'get'};
        $.ajax({
            type: 'GET',
            url: '/module/x_tunnel/control/config',
            data: pageRequests,
            dataType: 'JSON',
            success: function (result) {
                var server_selector = $("#server-selector");
                server_selector.find("option[value!='auto']").remove(); //$("#server-selector").empty();
                var selectable = result['server']['selectable'];
                for (var i in selectable) {
                    var record = selectable[i];
                    var new_option = document.createElement('option');
                    new_option.value = record[0];
                    new_option.text = record[1] + ' @ ' + record[2];
                    server_selector.append(new_option);
                }

                if (result['server']['available']) {
                    server_selector.val(result['server']['selected']);
                } else {
                    server_selector.val('auto');
                    tip('{{ _( "previously selected server nolonger available, automatically try " ) }}{{_("AUTO")}}', 'error');
                }

                $('#promoter').val(result['promoter']);
            },
            error: function (result) {
                displayErrorMessage();
            }
        });
    }

    function onAdvSettingSubmit() {
        $('button[type=submit]', '#adv-setting').html('{{ _("Please wait ...") }}');
        $('button[type=submit]', '#adv-setting').attr('disabled', 'disabled');

        var server = $("#server-selector").val();
<!--        var promoter = $("#promoter").val();-->
<!--        if (promoter.length != 0 && promoter.length != 8) {-->
<!--            tip('{{ _("Promoter is invalid.") }}', 'error', false);-->
<!--            window.refresh_timer.stop();-->
<!--            return;-->
<!--        }-->

<!--        var promote_code = window.promote_code;-->
<!--        if (promoter == promote_code){-->
<!--            tip('{{ _("Can\'t promote yourself.") }}', 'error', false);-->
<!--            window.refresh_timer.stop();-->
<!--            return;-->
<!--        }-->

        $.ajax({
            type: 'POST',
            url: '/module/x_tunnel/control/config?cmd=set',
            data: {
                'server': server,
<!--                'promoter': promoter-->
            },
            dataType: 'JSON',
            success: function (result) {
                $('button[type=submit]', '#adv-setting').html('{{ _("Submit") }}');
                $('button[type=submit]', '#adv-setting').removeAttr('disabled');

                if (result['res'] === 'success') {
                    tip('{{ _("Settings saved successfully.") }}', 'success');
                } else {
                    tip('{{ _( "Failed saving settings: " ) }}'+ result['reason'], 'error');
                }
            },
            error: function (result) {
                displayErrorMessage();
            }
        });
    }
</script>
<script type="text/javascript">
    $('#logout-trigger').click(function () {
        $.ajax({
            type: 'POST',
            url: '/module/x_tunnel/control/logout',
            dataType: 'JSON',
            success: function (result) {
                window.refresh_timer.stop();

                show_login_form();

                $('button[type=submit]', '#login-form').html('{{ _("Login") }}');
                // Fix bugs in Firefox
                $('button[type=submit]').removeAttr('disabled');
            },
            error: function (result) {
                tip('{{ _("Failed to log out.") }}', false);
            }
        });
    });
</script>
<script type="text/javascript">
    $('#charge-trigger').click(function () {
        window.refresh_timer.stop();
        $('.alert-warning', '#charge-modal').addClass('hide');
        $('#charge-modal').modal();
    });
</script>
<script type="text/javascript">
    $('.btn-primary', '#charge-modal').click(function () {
        $(this).attr('disabled', 'disabled');
        $(this).html('{{ _("Please refresh page.") }}');

        $('#charge-modal').submit();
    });
</script>
<script type="text/javascript">
    $('#transfer-credit-trigger').click(function () {
        $('.alert', '#transfer-credit-modal').addClass('hide');
        $('#transfer-credit-modal').modal();
    });
</script>
<script type="text/javascript">
    $('.btn-primary', '#transfer-credit-modal').click(function () {
        var transferAccount = $('#transfer-credit-username').val(),
            transferAmount  = $('#transfer-credit-amount').val();

        if (!isEmailLegal(transferAccount)) {
            $('.alert', '#transfer-credit-modal').html('{{ _("Transfer username seems not a valid Email address.") }}');
            $('.alert', '#transfer-credit-modal').removeClass('hide');
            return;
        }

        $('.btn-primary', '#transfer-credit-modal').attr('disabled', 'disabled');
        $('.btn-primary', '#transfer-credit-modal').html('{{ _("Please wait ...") }}');
        return doTransferCreditAction(transferAccount, transferAmount);
    });
</script>
<script type="text/javascript">
    function doTransferCreditAction(transferAccount, transferAmount) {
        var postData = {
            'to_account': transferAccount,
            'amount': transferAmount,
            'transfer_type': 'balance'
        };

        $.ajax({
            type: 'POST',
            url: '/module/x_tunnel/control/transfer',
            data: postData,
            dataType: 'JSON',
            success: function (result) {
                if (result['res'] == 'success') {
                    getUserInfo(1);
                } else {
                    $('.alert', '#transfer-credit-modal').html('{{ _("Error occurred: ") }}' + result['reason']);
                    $('.alert', '#transfer-credit-modal').removeClass('hide');
                }
                $('.btn-primary', '#transfer-credit-modal').removeAttr('disabled', 'disabled');
                $('.btn-primary', '#transfer-credit-modal').html('{{ _("Transfer") }}');
            }
        });
    }
</script>
<!--<script type="text/javascript">-->
<!--    $('#available-bandwidth').delegate('a.transfer', 'click', function () {-->
<!--        var maxAvailableBandwidth = $('.bandwidth', $(this).parent()).html(),-->
<!--            expireTime            = $('.expire-time', $(this).parent().parent()).attr('data-value');-->

<!--        $('.alert', '#transfer-bandwidth-modal').addClass('hide');-->
<!--        $('#transfer-bandwidth-amount').attr('placeholder', '{{ _("Max Available Bandwidth: ") }}' + maxAvailableBandwidth);-->
<!--        $('#bandwidth-expire-time').val(expireTime);-->

<!--        $('#transfer-bandwidth-modal').modal();-->
<!--    });-->
<!--</script>-->
<script type="text/javascript">
    $('.btn-primary', '#transfer-bandwidth-modal').click(function () {
        var transferAccount = $('#transfer-bandwidth-username').val(),
            transferAmount  = $('#transfer-bandwidth-amount').val(),
            expireTime      = $('#bandwidth-expire-time').val();

        if (!isEmailLegal(transferAccount)) {
            $('.alert', '#transfer-bandwidth-modal').html('{{ _("Transfer username seems not a valid Email address.") }}');
            $('.alert', '#transfer-bandwidth-modal').removeClass('hide');
            return;
        }

        $('.btn-primary', '#transfer-bandwidth-modal').attr('disabled', 'disabled');
        $('.btn-primary', '#transfer-bandwidth-modal').html('{{ _("Please wait ...") }}');
        return doTransferBandwidthAction(transferAccount, transferAmount, expireTime);
    });
</script>
<script type="text/javascript">
    function parseUnit(str) {
        var out = [0, ''];
        str = String(str);
        var num = parseFloat(str, 10);
        out[0] = num;
        out[1] = str.match(/[\d.\-\+]*\s*(.*)/)[1] || '';
        return out
    }

    function doTransferBandwidthAction(transferAccount, transferAmount, expireTime) {
        var amountUnit = parseUnit(transferAmount);
        if (amountUnit[1].toUpperCase() == "G") {
            var amount = amountUnit[0] * 1000 * 1000 * 1000;
        } else {
            var amount = amountUnit[0] * 1000 * 1000;
        }
        var postData = {
            'to_account': transferAccount,
            'amount': amount,
            'end_time': expireTime,
            'transfer_type': 'quota'
        };

        $.ajax({
            type: 'POST',
            url: '/module/x_tunnel/control/transfer',
            data: postData,
            dataType: 'JSON',
            success: function (result) {
                if (result['res'] == 'success') {
                    getUserInfo(1);
                } else {
                    $('.alert', '#transfer-bandwidth-modal').html('{{ _("Error occurred: ") }}' + result['reason']);
                    $('.alert', '#transfer-bandwidth-modal').removeClass('hide');
                }
                $('.btn-primary', '#transfer-bandwidth-modal').removeAttr('disabled', 'disabled');
                $('.btn-primary', '#transfer-bandwidth-modal').html('{{ _("Transfer") }}');
            }
        });
    }
</script>
<script type="text/javascript">
    function isDecimalNumber(obj) {
        var amountUnit = parseUnit(obj.value);
        if (isNaN(amountUnit[0])) {
            obj.value = '';
            return;
        }
        if (amountUnit[1].toUpperCase() != "G" && amountUnit[1].toUpperCase() != "M" && amountUnit[1] != "") {
            alert('{{ _("Unit should be M or G.") }}');
            return;
        }
        if (obj != null) {
            if (amountUnit[0].toString().split('.').length > 1 &&
                amountUnit[0].toString().split(".")[1].length > 2) {
                alert('{{ _("Transfer amount should not more than 2 decimal places.") }}');
            }
        }
    }
</script>
<!-- Plans -->
<script type="text/javascript">
    $('body').on('click', '.plan-trigger', function() {
        var title = $(this).attr('title');
        var plan = $(this).attr('id');
        orderPlan(title, plan);
    });

</script>
<script type="text/javascript">
    function orderPlan(planName, planValue) {
        window.refresh_timer.stop();
        $.ajax({
            data: {
                'product': 'x_tunnel',
                'plan': planValue
            },
            type: 'POST',
            url: '/module/x_tunnel/control/order',
            dataType: 'JSON',
            success: function (result) {
                if (result['res'] != 'success') {
                    if (result['reason'] == "balance not enough") {
                        $('#charge-plan', '#charge-modal').val(planName);
                        //$('.alert-warning', '#charge-modal').removeClass('hide');

                        $('#charge-modal').modal();
                    } else {
                        tip('{{ _("Failed to order: ") }}' + result['reason'], 'warning', false);
                    }
                } else {
                    getUserInfo(1);
                    tip('{{ _("Order successfully complete.") }}', 'info', false);
                }
            }
        });
    }
</script>
<script type="text/javascript">
    function getBillingHistory() {
        // TODO
        // Reference: function getHistory()
        // 
        // $('#billing-history').removeClass('hide');
        // $('#no-billing-history').addClass('hide');
    }
</script>
<!-- History -->
<script type="text/javascript">
    $('#get-history-button').click(function () {
        getHistory();

        $('#get-history-button').attr('disabled', 'disabled');
        $('#get-history-button').html('{{ _("Please wait ...") }}');
    });
</script>
<script type="text/javascript">
    function getHistory() {
        $('#history-list tbody').empty();

        $.ajax({
            type: 'GET',
            data: {
                'start': 1999999999,
                'end': 0,
                'limit': 1000
            },
            url: '/module/x_tunnel/control/get_history',
            dataType: 'JSON',
            success: function (result) {
                if (result['res'] != 'success') {
                    tip('{{ _("Get Fail:") }}' + result['reason'], 'warning', false);
                } else {
                    tipClose();
                }

                result['history'].forEach(function (entry) {
                    displayHistory(entry);
                });

                $('#get-history-button').html('{{ _("Get") }}');
                $('#get-history-button').removeAttr('disabled');
            }
        });
    }
</script>
<script type="text/javascript">
    function displayHistory(item) {
        var timestamp = item[0];
        var t = new Date(timestamp*1000);
        var timeString = t.getFullYear() + "-" + (t.getMonth()+1) + "-" + t.getDate() + " " + t.getHours() + ":" + t.getMinutes();

        var message = '';
        for (property in item[1]) {
            message += property + ':' + item[1][property] + '; ';
        }

        $('#history-list tbody').append('<tr><td>%s</td><td>%s</td></tr>'.format(timeString, message));
    }
</script>
